#include "FpsTimer.h"
#include <QtMath>
#include <QTimer>
#include <QTime>
#include "MediaCommon.h"

FpsTimer::FpsTimer(int fps, QObject *parent) : QObject(parent), fps(fps)
{
    unit = qFloor(1000.0 / fps);
    remainder = 1000 % fps;
    error = 0;
    estimate = unit * (fps - 2);

    timer = new QTimer(this);
    timer->setTimerType(Qt::TimerType::PreciseTimer);
    timer->setInterval(unit);
    connect(timer, &QTimer::timeout, this, &FpsTimer::timerTimeOut);
}

void FpsTimer::start()
{
    currentIndex = 0;
    startMillSecond = MediaCommon::currentMillSecond();
    lastMillSecond = startMillSecond;
    timer->start();
}

void FpsTimer::stop()
{
    timer->stop();
}

#include <QDebug>
void FpsTimer::timerTimeOut()
{
    ++currentIndex;
    if(currentIndex == 1){
        timer->setInterval(unit);
        lastMillSecond = MediaCommon::currentMillSecond();
        error = 0;
    }else if(currentIndex == fps){
        timer->setInterval(unit + startMillSecond - MediaCommon::currentMillSecond() - (error - estimate) / (fps - 2) + remainder);
        currentIndex = 0;
    }else{
        int currentMillSecond = MediaCommon::currentMillSecond();
        error += (currentMillSecond + 1000 - lastMillSecond) % 1000;
        lastMillSecond = currentMillSecond;
    }
    emit timeout();
}
